package com.cskaoyan.catmall.service.Impl;

import com.cskaoyan.catmall.config.keyword.DateUtils;
import com.cskaoyan.catmall.dao.WxCollectDao;
import com.cskaoyan.catmall.model.bo.WxAddOrDeleteBo;
import com.cskaoyan.catmall.model.bo.WxCollectListBo;
import com.cskaoyan.catmall.model.pojo.MarketCollect;
import com.cskaoyan.catmall.model.vo.WxCollectListVo;
import com.cskaoyan.catmall.model.vo.WxCollectVo;
import com.cskaoyan.catmall.service.WxCollectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 创建日期: 2022/01/10 14:28
 *
 * @author WangZhe
 * 备注:
 */

@Service
public class WxCollectServiceImpl implements WxCollectService {

    @Autowired
    WxCollectDao wxCollectDao;

    @Override
    public WxCollectListVo getList(Integer userId, WxCollectListBo wxCollectListBo) {
        Integer page = wxCollectListBo.getPage();//页码
        Integer limit = wxCollectListBo.getLimit();//数据量
        PageHelper.startPage(page, limit);

        if (wxCollectListBo.getType() != 0)
            try {
                throw new Exception("type为1的情况未考虑");
            } catch (Exception e) {
                e.printStackTrace();
            }

        List<WxCollectVo> list = wxCollectDao.getList(userId);
        PageInfo<WxCollectVo> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return WxCollectListVo.data(total, pages, limit, page, list);
    }

    @Override
    public void addOrDelete(Integer userId, WxAddOrDeleteBo wxAddOrDeleteBo) {
        Integer type = wxAddOrDeleteBo.getType();
        Integer valueId = wxAddOrDeleteBo.getValueId();
        if (type != 0)
            try {
                throw new Exception("type为1的情况未考虑");
            } catch (Exception e) {
                e.printStackTrace();
            }

        Integer id = wxCollectDao.selectCollectByValueId(userId, valueId);

        //如果查询不到deleted=0的数据则新建一个收藏, 如果查到了则将其修改为逻辑删除令delete=1
        if (id == null) {
            MarketCollect marketCollect = new MarketCollect();
            marketCollect.setUserId(userId);
            marketCollect.setValueId(valueId);
            marketCollect.setType(0);
            marketCollect.setAddTime(DateUtils.formatDate(new Date()));
            marketCollect.setUpdateTime(DateUtils.formatDate(new Date()));
            marketCollect.setDeleted(0);
            wxCollectDao.addCollect(marketCollect);
        } else {
            wxCollectDao.deleteCollect(id);
        }

    }
}
